package com.smiier.skin;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.o.app.media.PickContactTask;
import cn.o.app.media.PickContactTask.PickContactListener;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OActionSheet;
import cn.o.app.ui.OActionSheet.OActionItem;
import cn.o.app.ui.OActionSheet.OnActionItemClickListener;
import cn.o.app.ui.OImageView;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.lidroid.xutils.BitmapUtils;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.ConfirmCodeGetTask;
import com.smiier.skin.net.ConfirmCodeGetTask.ConfirmCodeGetRequest;
import com.smiier.skin.net.ConfirmCodeGetTask.ConfirmCodeGetResponse;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.util.ShareUtil;
import com.smiier.skin.util.StringArrayUtil;
import com.smiier.skin.utils.CommonUtility;

public class AddPatientActivity extends BasicActivity {
	protected OImageView mCodeView;
	protected OImageView mLogoImage;
	protected TextView mNameText;
	protected TextView mProfessionalText;
	protected TextView mHospitalText;
	protected EditText mContactText;
	protected ImageView mContactButton;
	protected TextView mSendSmsButton;
	protected RelativeLayout mScanQrcodeButton;
	int ConfirmCodeType = 8;
	protected BitmapUtils mBitmapUtils;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_patient);

		mBitmapUtils = new BitmapUtils(getContext());
		init();
		this.setNavTitle("添加患者");
	//	this.setNavRightBtnDrawable(R.drawable.btn_share);
		mCodeView = this.findViewById(R.id.code_view, OImageView.class);
		mLogoImage = this.findViewById(R.id.logo, OImageView.class);
		mNameText = this.findViewById(R.id.name, TextView.class);
		mProfessionalText = this
				.findViewById(R.id.professional, TextView.class);

		mHospitalText = this.findViewById(R.id.hospital, TextView.class);
		mContactText = this.findViewById(R.id.contact_text, EditText.class);
		mContactButton = this.findViewById(R.id.contact, ImageView.class);
		mSendSmsButton = this.findViewById(R.id.send_sms, TextView.class);
		mScanQrcodeButton = this.findViewById(R.id.scan_qrcode,
				RelativeLayout.class);
		mContactButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				PickContactTask task = new PickContactTask(
						AddPatientActivity.this,
						GlobalSettings.REQUEST_CODE_PICK_CONTACT);
				if (task.pickContact()) {
					task.setListener(new PickContactListener() {

						@Override
						public void onComplete(String name, List<String> phones) {
							int size = phones.size();
							if (size == 1) {
								mContactText.setText(phones.get(0));
							} else {
								List<OActionItem> items = new ArrayList<OActionSheet.OActionItem>();
								for (int i = 0; i < size; i++) {
									OActionItem item = new OActionItem();
									item.setText(phones.get(i));
									items.add(item);
								}
								OActionSheet<OActionItem> actionSheet = new OActionSheet<OActionSheet.OActionItem>(
										getContext());
								actionSheet.setDataProvider(items);
								actionSheet.show(false, true);
								actionSheet
										.setOnActionItemClickListener(new OnActionItemClickListener<OActionSheet.OActionItem>() {

											@Override
											public void onItemClick(
													OActionSheet<OActionItem> sheet,
													View v, int position,
													OActionItem dataItem) {
												mContactText.setText(dataItem
														.getText());
											}

										});
							}
						}
					});
				}
			}
		});

		text_right.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String url = GlobalSettings.SERVER_URL_TREATMENT
						+ "WeChat/MenuData/doctorHome/doctorid/"
						+ GlobalSettings.sUser.Uid;
				StringBuilder title = new StringBuilder();
				title.append(GlobalSettings.sUser.Name)
						.append("(")
						.append(StringArrayUtil
								.toString(GlobalSettings.sUser.Professional))
						.append(")");
				StringBuilder description = new StringBuilder();
				description
						.append(GlobalSettings.sUser.Hospital)
						.append(",")
						.append("擅长：")
						.append(StringArrayUtil
								.toString(GlobalSettings.sUser.Skilled));
				ShareUtil.share(getContext(), url, title, description);
			}
		});

		String logoUrl = GlobalSettings.SERVER_IMG_URL
				+ GlobalSettings.sUser.Pic;
		
		Log.i("testerror", "photo.pic:" + logoUrl);
		
//		if (logoUrl.lastIndexOf(".") == -1) {
			logoUrl += GlobalSettings.IMG_THUMB;
		/*}else{
			logoUrl +=GlobalSettings.Constant.IMG_TH;
		}*/
		
		
		Log.i("testerror", "photo.pic.end:" + logoUrl);
		
		
		// http://123.57.73.61/WeChat/MenuData/createQrcode/doctorid/153
		// mBitmapUtils.display(mLogoImage, logoUrl,
		// new OBitmapLoadCallBack<View>());
		
		
		CommonUtility.displayHeadImage(mLogoImage, mBitmapUtils, logoUrl,
				getResources(), GlobalSettings.sUser.Sex);
		mNameText.setText(GlobalSettings.sUser.Name);
		mProfessionalText.setText(StringArrayUtil
				.toString(GlobalSettings.sUser.Professional));
		mHospitalText.setText(GlobalSettings.sUser.Hospital);
		// mCodeView.setText(GlobalSettings.SERVER_URL
		// + "UrlControl/Follow_Set_ADD/" + GlobalSettings.sUser.User_Type
		// + "/" + GlobalSettings.sUser.Uid + "/download.aspx");
		mSendSmsButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getSmsCode();
			}
		});
		getQcrode();
	}

	private void getQcrode() {
		/*
		 * CreateQrcodeTask task = new CreateQrcodeTask(); CreateQrcodeRequest
		 * req = new CreateQrcodeRequest(); req.doctorid =
		 * GlobalSettings.sUser.Uid; task.setRequest(req); add(task);
		 * task.addListener(new
		 * NetTaskListener<CreateQrcodeTask.CreateQrcodeRequest,
		 * CreateQrcodeTask.CreateQrcodeResponse>() {
		 * 
		 * @Override public void onComplete( INetTask<CreateQrcodeRequest,
		 * CreateQrcodeResponse> task, CreateQrcodeResponse response) {
		 * toast(response.Res); }
		 * 
		 * @Override public void onException( INetTask<CreateQrcodeRequest,
		 * CreateQrcodeResponse> task, Exception e) { toast("cuowu "); } });
		 */
		new Thread() {
			public void run() {
				try {
					URL url = new URL(GlobalSettings.SERVER_URL_TREATMENT
							+ "WeChat/MenuData/createQrcode/doctorid/"
							+ GlobalSettings.sUser.Uid);
					URLConnection con = url.openConnection();
					InputStream is = con.getInputStream();

					BufferedInputStream bis = new BufferedInputStream(is);
					BufferedReader br = new BufferedReader(
							new InputStreamReader(bis));
					final StringBuilder sb = new StringBuilder();
					String s;
					while ((s = br.readLine()) != null) {
						sb.append(s);
					}
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							mBitmapUtils.display(mCodeView, sb.toString());
						}
					});
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();

	}

	public void onClick(View view) {
		super.onClick(view);

		// 添加扫描逻辑
		if (view.getId() == R.id.scan_qrcode) {
			Intent intent = new Intent(activity, ScanActivity.class);
			startActivityForResult(intent, 0);
		}
	}

	void getSmsCode() {
		String tel = mContactText.getText().toString();
		try {
			Long.parseLong(tel);
			if (!CommonUtility.isNull(tel)) {
				ConfirmCodeGetRequest req = new ConfirmCodeGetRequest();
				req.mobile = tel;
				req.ConfirmCodeType = ConfirmCodeType;
				ConfirmCodeGetTask task = new ConfirmCodeGetTask();
				task.setRequest(req);
				task.addListener(new NetTaskListener<ConfirmCodeGetTask.ConfirmCodeGetRequest, ConfirmCodeGetTask.ConfirmCodeGetResponse>() {

					@Override
					public void onComplete(
							INetTask<ConfirmCodeGetRequest, ConfirmCodeGetResponse> task,
							ConfirmCodeGetResponse response) {
						if (response.ResultCode == 200
								&& response.Res == GlobalSettings.IS_TRUE) {
							toast("验证码发送成功");

						}
					}

					@Override
					public void onException(
							INetTask<ConfirmCodeGetRequest, ConfirmCodeGetResponse> task,
							Exception e) {

					}

				});
				add(task);
			} else {
				toast("请输入手机号");
			}
		} catch (Exception e) {
			toast("请输入正确手机号");
		}
	}

	// 处理返回startActivityForResult
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		try {
			if (!CommonUtility.isNull(data)) {
				String info = data.getStringExtra(Constant.IDENTITY_KEY);
				JSONObject object = new JSONObject(info);
				final int userType = object.getInt("User_type");
				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put(Constant.PARAM_API, "User.Get");
				params.put("uids", object.getInt("Uid"));
				RequestTaskIntercept.requestIntercept(activity,
						Constant.URL.REQUEST, new RequestHandler(activity,
								new HandlerCallback() {
									@Override
									public void callback(Object o) {
										if (!CommonUtility.isNull(o)) {
											try {
												JSONObject object = (JSONObject) o;
												JSONArray array = object
														.getJSONArray(Constant.JSON_PARAM_RES);
												if (array.length() > 0) {
													object = array
															.getJSONObject(0);
													if (userType == 2) {
														Intent intent = new Intent(
																activity,
																DoctorDetailActivity.class);
														intent.putExtra(
																Constant.IDENTITY_KEY,
																object.toString());
														startActivity(intent);
													} else if (userType == 1) {

														// userType：1 为患者

														Intent intent = new Intent(
																activity,
																QuestionDetailActivity.class);
														intent.putExtra(
																Constant.IDENTITY_KEY,
																object.toString());
														intent.putExtra(
																Constant.IDENTITY_KEY_1,
																true);
														startActivity(intent);
													}
												}
											} catch (Exception e) {
												e.printStackTrace();
											}
										}
									}
								}), params);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
